package com.gqzmy.springboot3.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gqzmy.springboot3.entity.User;
import com.gqzmy.springboot3.exceptions.SystemApiException;
import com.gqzmy.springboot3.mapper.UserMapper;
import com.gqzmy.springboot3.service.dto.ServiceResultDTO;
import com.gqzmy.springboot3.vo.UserQuery;
import com.gqzmy.springboot3.vo.UserRegister;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author 周小哥  gqzmy@163.com 2022/12/1 11:11
 */

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResultDTO<User> register(UserRegister register) throws SystemApiException {
        if (Objects.nonNull(userMapper.getByUserAccount(register.userAccount()))) {
            return ServiceResultDTO.init(User.class).fail("已存在相同名称的用户");
        }
        User user = new User();
        BeanUtils.copyProperties(register, user);
        if (1 == userMapper.insertUser(user)) {
            return new ServiceResultDTO<User>().data(user);
        }
        throw SystemApiException.create().message("新增用户失败");
    }

    @Override
    public User getById(String id) {
        return userMapper.getById(id);
    }

    @Override
    public User getByName(String name) {
        return userMapper.getByUserAccount(name);
    }

    @Override
    public boolean insertUser(User user) {
        return 1 == userMapper.insertUser(user);
    }

    @Override
    public User updateUser(User user) {
        if (1 == userMapper.updateUser(user)) {
            return getById(user.getId());
        }
        throw new RuntimeException("更新用户异常");
    }

    @Override
    public PageInfo<User> getUserPageInfo(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getPagingBase().getPageNum(), userQuery.getPagingBase().getPageSize());
        List<User> userList = userMapper.getUserList(userQuery);
        return new PageInfo<>(userList);
    }

}
